package com.soxing.braindata.service.sync;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.soxing.braindata.dao.entity.Research;
import com.soxing.braindata.dao.entity.Site;
import com.soxing.braindata.dao.service.IResearchService;
import com.soxing.braindata.dao.service.ISiteService;
import com.soxing.braindata.domain.enumeration.FunTypeEnum;
import com.soxing.braindata.domain.response.sync.SyncResponse;
import com.soxing.braindata.domain.rpc.OriginSite;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 同步分中心
 */
@Slf4j
@Service("syncSiteService")
public class SyncSiteServiceImpl implements ISyncService<OriginSite> {
    @Resource
    private ISiteService siteService;
    @Resource
    private IResearchService researchService;

    @Override
    public SyncResponse syncData(OriginSite originSite) {
        try {
            Integer funType = originSite.getFunType();
            String sitePkId = originSite.getSitePkId();
            if (funType == null || sitePkId == null) {
                log.error("funType或subjectPkId为空。funType:{},subjectPkId:{}", funType, sitePkId);
                return SyncResponse.fail("funType或sitePkId为空");
            }
            sync(originSite);
            return SyncResponse.success();
        } catch (Exception e) {
            log.error("同步课题服务异常", e);
            return SyncResponse.fail();
        }
    }

    @Transactional
    void sync(OriginSite originSite) {
        Site site = createSite(originSite);
        siteService.remove(new LambdaQueryWrapper<Site>().eq(Site::getSitePkId, site.getSitePkId()));
        Integer funType = originSite.getFunType();
        if (funType == FunTypeEnum.DELETE.getFunType()) {
            return;
        }
        siteService.save(site);

        Research research = new Research();
        research.setSitePkId(originSite.getSitePkId());
        researchService.update(research, new LambdaQueryWrapper<Research>().eq(Research::getSubjectPkId, originSite.getSubjectPkId()));
    }

    private Site createSite(OriginSite originSite) {
        Site site = new Site();
        site.setSiteCode(originSite.getSiteCode());
        site.setSitePkId(originSite.getSitePkId());
        site.setSiteName(originSite.getSiteName());
        site.setPersonEmail(originSite.getPersonEmail());
        site.setPersonAccount(originSite.getPersonPkId());
        site.setAgencyCode(originSite.getAgencyCode());
        site.setAgencyName(originSite.getAgencyName());
        if(originSite.getType()==null){
            site.setType(0);
        }else{
            site.setType(originSite.getType());
        }
        return site;
    }
}
